package com.example.myapplication3;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import android.app.AlertDialog;
import android.app.ListActivity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import java.io.IOException;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class RateListActivity2 extends ListActivity implements Runnable,AdapterView.OnItemClickListener,AdapterView.OnItemLongClickListener {
    private static final String TAG ="List3Activity" ;  //AppCompatActivity
    private ArrayList<HashMap<String,String>> listItems;//存放文字、图片
    Handler handler;
    private SimpleAdapter listItemAdapter;//适配器
    private int msgWhat=7;
    SimpleAdapter adapter1;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.activity_list3);  AppCompatActivity
        //ListView list3=findViewById(R.id.mylist3);AppCompatActivity
        //data
        initListView();
        this.setListAdapter(listItemAdapter);
        MyAdapter adapter=new MyAdapter(this,R.layout.list_item,listItems);
        //list3.setAdapter(listItemAdapter); AppCompatActivity
        //getListView().setAdapter(listItemAdapter);与下一句同样功能
        Thread t=new Thread(this);
        t.start();
        handler = new Handler() {
            public void handleMessage(@NonNull Message msg) {
                if (msg.what == msgWhat) {
                    List<HashMap<String,String>> retList=(List<HashMap<String, String>>) msg.obj;
                    adapter1=new SimpleAdapter(RateListActivity2.this,retList,
                            R.layout.list_item,
                            new String[]{"ItemTitle","ItemDetail"},
                            new int[]{R.id.itemTitle,R.id.itemDetail});
                    setListAdapter(adapter1);
                    Log.i("handler","reset list...");
                }
                super.handleMessage(msg);
            }
        };
        getListView().setOnItemClickListener(this);
        getListView().setOnItemLongClickListener(this);
    }

    private void initListView() {
        listItems = new ArrayList<HashMap<String, String>>();
        for(int i=0;i<10;i++){
            HashMap<String,String>map=new HashMap<String,String>();//必须放在里面，map是多个
            map.put("ItemTitle","Rate:"+i);//标题文字
            Log.i(TAG,"rate"+i);
            map.put("ItemDetail","detatil:"+i);//详情描述
            listItems.add(map);
        }
        listItemAdapter=new SimpleAdapter(this,
                listItems,//listItem数据源
                R.layout.list_item,//Listitem的Xml布局，要有两个布局，一个是map的布局，还有一个本页面的布局
                new String[]{"ItemTitle","ItemDetail"},
                new int[]{R.id.itemTitle,R.id.itemDetail}
        );
    }
    @Override
    public void run() {
        Log.i("tread","run...");
        boolean marker=false;
        List<HashMap<String,String>> rateList=new ArrayList<HashMap<String, String>>();
        try {
            Document doc = Jsoup.connect("https://www.boc.cn/sourcedb/whpj/").get();
            Elements tables = doc.getElementsByTag("table");
            Log.i(TAG, "run: "+doc.title());
            Element table6 = tables.get(1);
            Elements tds = table6.getElementsByTag("td");//Elements是一个集合
            for (int a = 0;a<tds.size();a+=8) {
                if (tds.size() > 0) {
                    String str = tds.get(a).text();
                    Log.i(TAG, "run:td:" + str);
                    String val = tds.get(a+5).text();
                    Log.i(TAG, "run: rate:" + val);

                    HashMap<String,String> map=new HashMap<String, String>();
                    map.put("ItemTitle",str);
                    map.put("ItemDetail",val);

                    rateList.add(map);
                    Log.i("td",str+">"+val);
                }
                marker=true;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //返回数据给主线程
        Message msg = handler.obtainMessage();
        msg.what=msgWhat;
        if(marker){
            msg.arg1=1;
        }else{
            msg.arg1=0;
        }

        msg.obj=rateList;
        handler.sendMessage(msg);

        Log.i("tread","sendMessage...");
    }


    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i(TAG,"onItemClick:position="+position);
        Object itemAtPosition=getListView().getItemAtPosition(position);
        HashMap<String,String>map=(HashMap<String,String>) itemAtPosition;
        String titleStr=map.get("ItemTitle");
        String detailStr=map.get("ItemDetail");
        Log.i(TAG,"onItemClick:titlestr="+titleStr);
        Log.i(TAG,"onItemClick:detailstr="+detailStr);

        TextView title=(TextView) view.findViewById(R.id.itemTitle);
        TextView detail=(TextView) view.findViewById(R.id.itemDetail);
        String title2=String.valueOf(title.getText());
        String detail2=String.valueOf(detail.getText());
        Log.i(TAG,"onItemClick:title2="+title2);
        Log.i(TAG,"onItemClick:detail2="+detail2);

        Intent intent=new Intent(this,RateListSaveActivity.class);
        intent.putExtra("titlestr",titleStr);
        intent.putExtra("detailstr",detailStr);
        startActivity(intent);
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
        Log.i(TAG,"onItemCick"+"长按事件处理");
        //长按时显示对话框
        AlertDialog.Builder builder=new AlertDialog.Builder(this);
        builder.setTitle("提示");
        builder.setMessage("请确认是否删除当前数据");
        builder.setPositiveButton("是", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Log.i(TAG,"onClick:对话框事件处理");
                //删除数据项
                //adapter1.remove(getListView().getItemAtPosition(position));
                listItems.remove(position);
                adapter1.notifyDataSetChanged();
            }
        }).setNegativeButton("否",null);
        builder.create().show();
        return false;
    }

}